<?php

namespace App\Models\Clickhouse\Guanyuan;

use App\Models\Clickhouse\BaseCHModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Service\Kms\Home\HomeService;
use App\Service\Kms\Task\UserRoleService;
use Kuafu\LaravelClickHouse\Database\Eloquent\Builder;

class GyDmDaySalesAnalyseCHModel extends BaseCHModel
{
    protected $table = 'gy_dm_day_sales_analyse';

    /**
     * 首页查询条件构造
     *
     * @param int $role
     * @param int $regionSelectionType
     * @param string $region
     * @return Builder
     */
    public static function buildHomeSearchQuery(int $role, int $regionSelectionType, string $region): Builder
    {
        $query = null;
        if ($role == UserRoleService::ROLE_BASE_SUPERVISOR) {
            $signOrder = OpenShopSignOrderModel::query()->whereHas("checkAcceptRel", function ($query) {
                $query->where("managerId", auth()->user()->rmsUserId);
            })->get();
            if ($signOrder->isNotEmpty()) {
                $query = function ($query) use ($signOrder) {
                    $query->whereIn("storeCode", $signOrder->pluck("shopCode")->toArray());
                };
            }
        } else {
            switch ($regionSelectionType) {
                case HomeService::REGION_SELECTION_TYPE_1:
                    $query = function ($query) use ($region) {
                        $query->where("region", "LIKE", "%" . str_replace("分公司", "", $region) . "%");
                    };
                    break;
                case HomeService::REGION_SELECTION_TYPE_2:
                    $query = function ($query) use ($region) {
                        return $query->where("provinceWhereTheStoreIsLocated", $region);
                    };
                    break;
                case HomeService::REGION_SELECTION_TYPE_3:
                    $query = function ($query) use ($region) {
                        return $query->where("cityWhereTheStoreIsLocated", $region);
                    };
                    break;
            }
        }

        return self::query()->when($query, function ($subQuery) use ($query) { return $subQuery->where($query); });
    }
}
